<template>
  <!-- 导入用户信息 -->
  <el-dialog
    v-model="visible"
    :modal="false"
    :title="type === 0?$t('user.clientImport'):$t('user.userImport')"
    :close-on-click-modal="false"
    width="38%"
  >
    <span
      v-for="(note, i) in (isEn() ? notesEn : notes)"
      :key="note"
    >{{ note }}<br v-if="i < notes.length - 1"></span>
    <el-button
      style="margin-left: 10px;"
      link
      type="primary"
      @click="downloadModel"
    >
      {{ $t('product.downloadTemplate') }}
    </el-button>
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      :file-list="files"
      :action="actionUrl"
      :headers="{Authorization: cookie.get('bbcAuthorization_vs'),locale:lang}"
      :limit="1"
      name="excelFile"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-error="uploadFalse"
      :on-success="uploadSuccess"
      :auto-upload="false"
      :before-upload="beforeAvatarUpload"
      :on-change="onFileChange"
    >
      <template #trigger>
        <el-button
          type="success"
        >
          {{ $t('product.selectFile') }}
        </el-button>
      </template>
      <el-button
        style="margin-left: 10px;"
        type="primary"
        @click="submitUpload"
      >
        {{ $t('components.confirmUpload') }}
      </el-button>
    </el-upload>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import cookie from 'vue-cookies'

const props = defineProps({
  type: {
    default: 0,
    type: Number
  }
})

const emit = defineEmits(['refreshDataList'])

const actionUrl = computed(() => {
  return http.adornUrl(props.type === 0 ? '/user/user/importCustomerExcel' : '/user/user/importUserExcel')
})

const lang = reactive(localStorage.getItem('bbcLang') || 'zh_CN')
const notes = ref([])
const notesEn = ref([])

onMounted(() => {
  notes.value = props.type === 1 ? [
    '注意：',
    '   1、请勿修改表格中的字段顺序，或随意增加、删除表格字段,上传模板大小不能超过 10MB,超过应该分批导入',
    '   2、会员等级根据配置成长值等级自动设置',
    '   3、导入用户期间，请勿修改会员等级设置',
    '   4、根据手机号(必须是11位)/邮箱作为唯一标识，如果导入的手机号/邮箱已存在，不会更新用户的任何数据.',
    '   5、国家/地区不同，手机号的验证规则也不同，导入时不会验证手机号码/邮箱的真实性，请谨慎填写，导入错误数据请自行负责.'
  ] : [
    '注意：',
    '   1、请勿修改表格中的字段顺序，或随意增加，删除表格字段，上传模板大小不能超过10MB.超过应该分批导入。',
    '   2、根据手机号(必须是11位)作为唯一标识，如果导入的手机号已存在，不会更新用户的任何数据。',
    '   3、国家/地区不同，手机号的验证规则也不同，导入时不会验证手机号码的真实性，请谨慎填写，导入错误数据请自行负责。'
  ]
  notesEn.value = props.type === 1 ? [
    ' Note: ',
    ' 1, Please do not modify the order of the fields in the form, or arbitrarily add or delete form fields, upload the template size can not exceed 10MB, more than should be imported in batches ',
    ' 2、The Member level is set automatically according to the configured growth value level ',
    ' 3、Do not modify the membership level settings during user import ',
    ' 4、According to the cell phone number/Email as a unique identification, if the imported cell phone number/Email already exists, will not update any data of the user.',
    ' 5、The verification rules for cell phone numbers are different for different countries/regions, and the authenticity of cell phone numbers will not be verified when importing, so please fill in the form carefully and be responsible for importing wrong data.'
  ] : [
    ' Note: ',
    ' 1, Do not modify the order of the fields in the form, or add or delete the fields of the form at will. The size of the uploaded template cannot exceed 10MB. The excess should be imported in batches ',
    ' 2, Based on the phone number (which must be 11 digits) as a unique identifier, if the imported phone number already exists, no data will be updated for the user ',
    ' 3, The verification rules of the mobile phone number are different in different countries/regions. The authenticity of the mobile phone number will not be verified when importing. Please fill in the data carefully '
  ]
})

const files = ref([])
const visible = ref(false)
const uploadSuccess = (response) => {
  let msg = response.data.msg + '！'
  if (response.data.errorRowInfos && response.data.errorRowInfos.length) {
    msg += response.data.errorRowInfos.reduce((total, item) => {
      if (total === '') {
        total += '["'
      } else {
        total += ',"'
      }
      return total + item + '"'
    }, '') + ']'
  }
  alert(msg)
  files.value = []
  visible.value = false
  emit('refreshDataList')
}

const uploadFalse = () => {
  alert(isEn() ? 'File upload failed!' : '文件上传失败！')
}

const init = () => {
  visible.value = true
}

// 上传前对文件的大小的判断
const beforeAvatarUpload = (file) => {
  const extension = file.name.split('.')[1] === 'xls'
  const extension2 = file.name.split('.')[1] === 'xlsx'
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!extension && !extension2) {
    alert(isEn() ? 'Upload template can only be in xls, xlsx format!' : '上传模板只能是 xls、xlsx格式!')
  }
  if (!isLt2M) {
    alert(isEn() ? 'Upload template size cannot exceed 10MB' : '上传模板大小不能超过 10MB!')
  }
  return extension || (extension2 && isLt2M)
}

const uploadRef = ref(null)
const submitUpload = () => {
  // 触发组件的action
  if (!files.value?.length) {
    ElMessage.error($t('order.uploadInvoiceTip'))
    return
  }
  uploadRef.value?.submit()
}

const handleRemove = () => {}

const handlePreview = (file) => {
  if (file.response.status) {
    alert(isEn() ? 'This file import success' : '此文件导入成功')
  } else {
    alert(isEn() ? 'This file import failed' : '此文件导入失败')
  }
}

const onFileChange = (filePar, filesPar) => {
  files.value = filesPar
}

// 下载模板
const downloadModel = () => {
  http({
    url: http.adornUrl('/user/user/downloadTemplate'),
    method: 'get',
    params: http.adornParams({ templateType: props.type }),
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(({ data }) => {
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = props.type === 1 ? $t('user.importMemberMode') : $t('user.importClientMode')
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}

const isEn = () => {
  return $t('language') === 'English'
}

defineExpose({
  init
})

</script>
